/**
 * IM SDK连接
 */

var data = {
    friendlist: [],
    sessions: []
};
var isSwitch = false;
var href = window.location.href;
var debugFlag = false;
var appKey = '211cf33f06ece9b9934e91612362e2b8';
// 正式环境和测试环境
if (location.href.indexOf('88ba.com') > -1 || location.href.indexOf('wph.com') > -1) {
    debugFlag = true;
    appKey = 'a125681a970e694ef118a9f8ac497ff6';
}

function login() {
    window.nim = new NIM({
        debug: debugFlag,
        db: false,
        appKey: appKey,
        account: globalData.guest_im_info.accid,
        token: globalData.guest_im_info.im_token,
        syncSessionUnread: true,
        currSess: '',
        currScene: 'p2p',
        onconnect: function onConnect() {
            console.log('网易IM连接成功');
        },
        onwillreconnect: onWillReconnect,
        ondisconnect: onDisconnect,
        onerror: onError,
        //好友
        onfriends: onFriends,
        // 会话
        onsessions: onSessions,
        onupdatesession: onUpdateSession,
        setCurrSession: setCurrSession,
        // 消息
        onroamingmsgs: onRoamingMsgs,
        onofflinemsgs: onOfflineMsgs,
        onmsg: onMsg,
        // 同步完成
        onsyncdone: onSyncDone,
        onsysmsg: onSysMsg,
    });
}

function onWillReconnect(obj) {
    // 此时说明 `SDK` 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
    console.log('即将重连');
    // console.log(obj.retryCount);
    // console.log(obj.duration);
}

function onDisconnect(error) {
    // 此时说明 `SDK` 处于断开状态, 开发者此时应该根据错误码提示相应的错误信息, 并且跳转到登录页面
    console.log('丢失连接');
    console.log(error);
    if (error) {
        switch (error.code) {
            // 账号或者密码错误, 请跳转到登录页面并提示错误
            case 302:
                break;
            // 被踢, 请提示错误后跳转到登录页面
            case 'kicked':
                break;
            default:
                break;
        }
    }
}

function onError(error) {
    console.log(error);
}

function onSysMsg(sysMsg) {
    console.log('收到系统通知', sysMsg);
    if (sysMsg.type == "addFriend") {
        nim.getUser({
            account: sysMsg.from,
            sync: true,
            done: function (error, user) {
                if (!error) {
                    data.friendlist.push(user);
                }
            }
        })
    }
}

function onFriends(friends) {
    var friendlist = friends;
    data.friendlist = nim.mergeFriends(friendlist, friends);
};

function onAddFriend(friend) {
    data.friends = nim.mergeFriends(data.friends, friend);
}

function onSessions(sessions) {
    //获取所有会话的未读消息
    var msgData = {};
    for (var i = 0; i < sessions.length; i++) {
        //如果有缓存消息，则将缓存消息的数量并入新的会话列表中
        if (data.sessions.length != 0) {
            var storageSess = data.sessions;
            for (var j = 0; j < storageSess.length; j++) {
                if (storageSess[j].to == sessions[i].to) {
                    sessions[i].unread += storageSess[j].unread;
                    break;
                }
            }
        }

        var group = sessions[i];
        var session = group.to;
        if (!msgData[session]) {
            msgData[session] = {};
        }
        msgData[session].unread = group.unread;
        msgData[session].pullMsg = 0;
        if (group.lastMsg.type == 'image') {
            group.lastMsg.text = '[图片]'
        } else if (group.lastMsg.type == 'notification') {
            if (group.lastMsg.attach.type == "passTeamApply") {
                group.lastMsg.text = '进入聊天室'
            }
            if (group.lastMsg.attach.type == 'leaveTeam') {
                group.lastMsg.text = '退出聊天室'
            }
        }
        msgData[session].lastMsg = group.lastMsg;
    }
    data.sessions = sessions;
}

function onUpdateSession(session) {
    if (!session.lastMsg) {
        return
    }
    if (session.lastMsg.type == 'notification' && session.lastMsg.attach != undefined && session.lastMsg.attach.type != "passTeamApply") {
        return
    }
    console.log('会话更新了', session);

    session.lastMsg = parseMsg(session.lastMsg);
    if (session.lastMsg == undefined) {
        return
    }
    if (session.lastMsg && session.lastMsg.text.indexOf('chat-img') > 0) {
        session.lastMsg.text = '[图片]'
    }
    if (session.to == nim.currSess) {
        setSessionUnread(session.to);
    }
    if (session.lastMsg.type == 'text') {
        data.sessions = nim.mergeSessions(data.sessions, session);
    }

    // 如果是当前工程商的消息
    if (session.to == globalData.im_info.accid) {
        displayUnreadNum(session.unread);
    }
}

function onRoamingMsgs(obj) {
    // console.log('漫游消息', obj);

}

function onOfflineMsgs(obj) {
    // console.log('离线消息', obj);
    // pushMsg(obj.msgs);
}

function onMsg(msg) {
    console.log('收到消息', msg.scene, msg.type, msg);
    // 如果是自己发的，或者工程商发的，才显示到当前面板中
    if (msg.from == globalData.im_info.accid) {
        var content = JSON.parse(msg.content).data;
        if(msg.type == 'custom' && content.type == 0){
            msg.type = 'text';
            msg.text = content.msg;
        }else{
            msg.type = 'text';
            msg.text = '[未知消息类型]';
        }
        displayMsg(msg);
    }
}

function parseMsg(msg) {
    //如果是图片消息,改造一下
    if (msg.type == 'image') {
        msg.type = 'text';
        msg.text = "<img class='chat-img' src='" + msg.file.url + "' evt='scanBig' />"
    }
    // if(msg.type != 'text'){
    //     return msg
    // }
    var sessid = '';
    if (msg.scene == 'team') {
        sessid = msg.target;
    }
    return msg
}

function pushMsg(msgs) {
    if (!Array.isArray(msgs)) {
        msgs = [msgs];
    }
    var sessionId = msgs[0].sessionId;
    data.msgs = data.msgs || {};
    data.msgs[sessionId] = nim.mergeMsgs(data.msgs[sessionId], msgs);
}

function onSyncDone() {
    // console.log('同步完成');
    $(document.body).trigger('imInit');
    // 加好友
    // AddSupplierFriend();
}

/**
 * 设置当前会话，当前会话未读数会被置为0，同时开发者会收到 onupdatesession回调
 * @param {String} scene
 * @param {String} to
 */
function setCurrSession(sel) {
    //将切换前的会话的未读数置为0
    if (sel) {
        isSwitch = true;
    }
    nim.currSess = sel;
    nim.currScene = 'p2p';//现在只有p2p关系
    //调用网易切换会话的方法,是为了将消息未读数重置为0;
    nim.setCurrSession('p2p' + '-' + sel);

    //将切换后的会话的未读数置为0
    setSessionUnread(sel);

}

// 将data中的session未读数重置为0
// 将项目中记录的未读数值也更改
function setSessionUnread(sessionId) {
    for (var i = 0; i < data.sessions.length; i++) {
        if (data.sessions[i].to == sessionId) {
            data.sessions[i].unread = 0;
        }
    }
}

// 获取历史纪录
function loadHistroy(sid, succ, fail) {
    // 如果是伪造的聊天回话，则不请求
    var hasSave = localStorage.getItem('hasSavePhone');
    if (nim.currSess == '4fake' && project.data.user.user_type == 0 && !hasSave) {
        var fakeMsg = [{
            type: 'fakeNew',
            from: '4',
            text: '<div class="one-message"><img class="user-head-icon" src="/images/imodules/ServiceIcon/jvhua.jpg"><div class="msgbody"><div class="fakeSavePhone"><h5>请先登记排队</h5><input class="form-control mobile" type="tel" placeholder="手机号码" /><button class="btn btn-primary" ievent="saveMobile">继续咨询</button></div><img class="triangle" src="/images/imodules/ServiceIcon/triangle2.png"></div></div>',
            flow: 'in'
        }, {
            type: 'fakeNew',
            from: '4',
            text: '<div class="one-message system-msg"><span>当前还有1人排队，大约需等待11秒</span></div>',
            flow: 'in'
        }]
        succ(fakeMsg);
        return
    }
    // 正常获取历史纪录逻辑
    var lastTime = new Date().getTime();
    nim.getHistoryMsgs({
        scene: 'p2p',
        endTime: lastTime,
        to: sid,
        done: function (error, obj) {
            console.log('获取好友历史消息' + (!error ? '成功' : '失败'));
            if (!error) {
                var cloudMsg = obj.msgs;
                if (cloudMsg) {
                    for (var i = 0, j = cloudMsg.length; i < j; i++) {
                        cloudMsg[i] = parseMsg(cloudMsg[i]);
                    }
                    if (cloudMsg.length > 0) {
                        succ(cloudMsg);
                    } else {
                        // 如果历史消息为空，则造一条假的消息，以便洽谈室的历史消息监听能够获得通知，从而移除loading动画；
                        var fakeMsg = [{
                            type: 'fake',
                        }]
                        if (nim.currSess == '4') {
                            fakeMsg = [{
                                type: 'text',
                                from: '4',
                                text: '您好，有什么需要咨询吗？',
                                flow: 'in'
                            }]
                        }
                        succ(fakeMsg);
                    }
                    succ(cloudMsg);
                }
            } else {
                fail();
            }
        }
    });
}

/**
 * 发送普通文本消息
 */
function sendTextMessage(text, cb) {
    if (nim.currSess == '') {
        cb && cb.fail();
        return
    }
    // 通过自定义消息的方式发送
    var content = {
        "data":{"msg": text,"type": 0},
        "msg_type":20
    }
    nim.sendCustomMsg({
        scene: 'p2p',
        to: nim.currSess,
        content:  JSON.stringify(content),
        done: function (error, msg) {
            if (!error) {
                cb && cb.succ(msg);
            } else {
                cb && cb.fail(error)
            }
        }
    });
};

/**
 * 发送图片消息
 */
function sendImageServ() {
    $('.sendImgPending_serv').removeClass('hide');
    nim.sendFile({
        scene: nim.currScene,
        to: nim.currSess,
        type: 'image',
        fileInput: 'imgFile_serv',
        beginupload: function (upload) {
            // - 如果开发者传入 fileInput, 在此回调之前不能修改 fileInput
            // - 在此回调之后可以取消图片上传, 此回调会接收一个参数 `upload`, 调用 `upload.abort();` 来取消文件上传
        },
        uploadprogress: function (obj) {
            console.log('文件总大小: ' + obj.total + 'bytes');
            console.log('已经上传的大小: ' + obj.loaded + 'bytes');
            console.log('上传进度: ' + obj.percentage);
            console.log('上传进度文本: ' + obj.percentageText);
        },
        uploaddone: function (error, file) {
            console.log(error);
            console.log(file);
            console.log('上传' + (!error ? '成功' : '失败'));
            if (!error) {
                $('.sendImgPending_serv').addClass('hide');
            }
        },
        beforesend: function (msg) {
            console.log('正在发送image消息, id=' + msg.idClient);
        },
        done: function () {
            console.log('发送完成')
        }
    });
}

/**
 * 发送图片消息
 */
function sendImage() {
    $('.sendImgPending').removeClass('hide');
    nim.sendFile({
        scene: 'p2p',
        to: nim.currSess,
        type: 'image',
        fileInput: 'imgFile',
        beginupload: function (upload) {
            // - 如果开发者传入 fileInput, 在此回调之前不能修改 fileInput
            // - 在此回调之后可以取消图片上传, 此回调会接收一个参数 `upload`, 调用 `upload.abort();` 来取消文件上传
        },
        uploadprogress: function (obj) {
            console.log('文件总大小: ' + obj.total + 'bytes');
            console.log('已经上传的大小: ' + obj.loaded + 'bytes');
            console.log('上传进度: ' + obj.percentage);
            console.log('上传进度文本: ' + obj.percentageText);
        },
        uploaddone: function (error, file) {
            console.log(error);
            console.log(file);
            console.log('上传' + (!error ? '成功' : '失败'));
            if (!error) {
                $('.sendImgPending').addClass('hide');
            }
        },
        beforesend: function (msg) {
            console.log('正在发送image消息, id=' + msg.idClient);
        },
        done: function () {
            console.log('发送完成')
        }
    });
}

//获取单个好友的详细资料
function getUser(id) {
    var info = getSupplierInfo(id);
    if (id == project.data.user.user_id || id == '3') {
        return;
    }
    if (!info || info.avatar == '') {
        nim.getUser({
            account: id,
            sync: true,
            done: function (error, user) {
                if (!error) {
                    return user;
                }
            }
        })
    } else {
        return info;
    }

}

//直接添加好友（无需验证）
function addFriend(account, cb) {
    nim.addFriend({
        account: account + '',
        done: function (error, obj) {
            if (!error) {
                //更新好友列表及其资料
                data.friendlist.push(obj.friend);
                cb && cb.succ(obj);
            } else {
                cb && cb.fail && cb.fail();
            }
        }
    });
}


/** ==============================  业务逻辑代码  ===============================*/

var msgPane;

function imInit() {
    login();
    //聊天界面
    msgPane = $('.msg-pane');
    //输入框输入事件监听
    $('#input_serv').on('input propertychange blur', function () {
        //聊天面板滚到底部3t
        msgPane[0].scrollTop = msgPane[0].scrollHeight;
    });
// 输入框enter提交事件
    $('.input-pane_serv').on('submit', function (e) {
        e.preventDefault();
        // submitMsg();
    });
}


// im连接完成后，自动加工程商为好友
function AddSupplierFriend() {
    addFriend(globalData.im_info.accid, {
        succ: function (json) {
            console.log('加好友成功');
            sendWelcomeToClient();
        },
        fail: function (json) {
            console.log('000')
        }
    })
}

// 自动发送一条消息给当前用户
function sendWelcomeToClient() {
    var text = "您好，请问有什么可以帮您？";
    if (globalData.sem.word) {
        "您好，在找“" + globalData.sem.word + "”？"
    }
    var data = {
        "from_id": globalData.im_info.accid+"",
        "to_id": globalData.guest_im_info.accid+"",
        "content": text
    };
    $.ajax({
        url: APIURL + "/enterprise/send_im_message",
        type: "POST",
        dataType: "json",
        data: JSON.stringify(data),
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        contentType: 'application/json',
        success: function () {
            console.log("消息发送成功")
        }
    })

    // 待补充
}

// 未读消息显示
function displayUnreadNum(unreadNum) {
    var dom = $('#onLineChat .unread-num');
    if (unreadNum == 0) {
        dom.hide().html('0');
    } else {
        if (unreadNum > 99) {
            unreadNum = '…'
        }
        dom.html(unreadNum).show();
    }
}

function submitMsg() {
    var text = $('#input_serv').val();
    if (text.length > 0 && text.trim().length > 0) {
        sendTextMessage(text, {
            succ: function (msg) {
                console.log('发送成功');

                msg.type = 'text';
                msg.text = text;
                displayMsg(msg);

                clearInput();
                postMessagesToServer(text,msg.time);
            },
            fail: function (err) {
                alert('发送失败')
            }
        });
    }
}
// 发送消息后，通知服务端保存
function postMessagesToServer(text,time){
    var content = {
        "msg": text,"type": 0
    }
    var data = {
        "message_list":[
            {
                "from_id": globalData.guest_im_info.accid,
                "to_id": globalData.im_info.accid+'',
                "message": JSON.stringify(content),
                "created_at": time
            }
        ]
        
    }
    $.ajax({
        url: APIURL+"/v2/anonymous/messages",
        type: "POST",
        dataType: "json",
        data: JSON.stringify(data),
        timeout: 30000,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        contentType: 'application/json',
        success: function (json, status, xhr) {
        }

    });
}

function clearInput() {
    $("#input_serv").val('').focus();
}

function displayMsg(msg) {
    var fromAccount = msg.from;
    var isSelfSend = msg.flow == 'out';//消息是否为自己发的
    var subType = msg.type;//消息类型
    var triangle, userhead;
    var onemsg = '';
    //普通消息
    if (subType == 'text') {
        //如果自己发的消息
        if (isSelfSend) {
            var src = './img/client.png';
            userhead = '<img class="user-head-icon" src="' + src + '"/>';
            //小三角
            triangle = '<img class="triangle" src="./img/triangle1.png">';
            onemsg = '<div class="one-message self-msg">' + userhead +
                '<div class="msgbody"><pre>' + msg.text + '</pre>' + triangle +
                '</div></div>'
        }
        //不是自己发的消息
        else {
            //小三角
            triangle = '<img class="triangle" src="./img/triangle2.png">';
            var src1 = globalData.im_info.avatar;
            userhead = '<img class="user-head-icon" src="' + src1 + '"/>';
            onemsg = '<div class="one-message">' + userhead +
                '<div class="msgbody"><pre>' + msg.text + '</pre>' + triangle +
                '</div></div>'
        }
    }
    //如果是图片,去掉<pre>标签
    if (onemsg.indexOf('chat-img') > 0) {
        onemsg = onemsg.replace('<pre>', '').replace('</pre>', '');
    }
    msgPane.append(onemsg);

    var delayTime = 300;
    //如果消息中没有图片,就加快显示速度
    if (onemsg.indexOf('chat-img') < 0) {
        delayTime = 30;
    }
    //图片加载需要时间,延迟滚动
    setTimeout(function () {
        msgPane[0].scrollTop = msgPane[0].scrollHeight;
    }, delayTime);
}